package db;
import java.util.*;
/**
 * the class of SimpleLogger is 
 * used to print message to the console
 * 
 * it has only one instance
 * @author wangkaidi
 *
 */
public class SimpleLogger 
{
	public final static int DEBUG=0;
	public final static int INFO=1;
	public final static int WARNING=2;
	public final static int FATAL=3;
	
	private static SimpleLogger logger;
	private SimpleLogger()
	{		
	}
	
	/**
	 * get the logger instance
	 * @return
	 */
	public synchronized static SimpleLogger getInstance()
	{
		if(logger==null)
		{
			logger=new SimpleLogger();
		}
		return logger;
	}
	
	private LogListener listener;
	public void setListener(LogListener listener)
	{
		this.listener=listener;
	}
	
	public void removeListener()
	{
		this.listener=null;
	}
	
	private int currentlevel=DEBUG;
	public void log(int level,String message)
	{
		if(level<currentlevel)return;
		System.out.println(getLogMessage(level,message));
		if(listener!=null)listener.log(getLogMessage(level,message));//notify the listener
	}
	
	public void setLevel(int level)
	{
		this.currentlevel=level;
	}
	
	private String getLogMessage(int level,String message)
	{
		StringBuffer sb=new StringBuffer();
		sb.append(this.getDateString());
		sb.append("\n");
		sb.append(this.getLevelString(level));
		sb.append(" ");
		sb.append(message);
		sb.append("\n");
		return sb.toString();
	}
	
	/**
	 * return a String represent the current date
	 * @return
	 */
	public String getDateString()
	{	
		Calendar cal=Calendar.getInstance();
		int year=cal.get(Calendar.YEAR);
		int month=cal.get(Calendar.MONTH);
		int day=cal.get(Calendar.DAY_OF_MONTH);
		int hour=cal.get(Calendar.HOUR_OF_DAY);
		int minute=cal.get(Calendar.MINUTE);
		int second=cal.get(Calendar.SECOND);
		String hourstring,minutestring,secondstring;
		if(hour<10)hourstring="0"+hour;
		else hourstring=""+hour;
		if(minute<10)minutestring="0"+minute;
		else minutestring=""+minute;
		if(second<10)secondstring="0"+second;
		else secondstring=""+second;
		return "["+year+"-"+month+"-"+day+" "+hourstring+":"+minutestring+":"+secondstring+"]";
	}
	
	/**
	 * return a string represents the level
	 * @param level
	 * @return
	 */
	private String getLevelString(int level)
	{
		if(level==DEBUG)
		{
			return "[DEBUG]";
		}
		else if(level==INFO)
		{
			return "[INFO]";
		}
		else if(level==WARNING)
		{
			return "[WARNING]";
		}
		else if(level==FATAL)
		{
			return "[FATAL]";
		}
		else
		{
			return "[UNKNOWN]";
		}
	}
}
